package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpLogService empLogService;

    @Override
    public LoginInfo login(Emp emp) {
        // 通过用户名与密码查询员工表，只会返回一条记录
        Emp empDB = empMapper.selectByUsernameAndPassword(emp);
        // 如果没有查到数据，返回的null
        if(null != empDB){
            // 用户名与密码是正确的
            // 构建登录用户的信息返回
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setId(empDB.getId());
            loginInfo.setUsername(empDB.getUsername());
            loginInfo.setName(empDB.getName());
            // 生成token
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",empDB.getId());//必须有id，后续开发的功能需要用到
            claims.put("username",empDB.getUsername());
            String token = JwtUtils.generateJwt(claims);
            loginInfo.setToken(token);
            return loginInfo;
        }
        return null;
    }

    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        List<Emp> empList = empMapper.list(empQueryParam);
        Page<Emp> pageInfo = (Page<Emp>) empList;
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getResult());
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void add(Emp emp) {
        try {
            LocalDateTime now = LocalDateTime.now();
            emp.setCreateTime(now);
            emp.setUpdateTime(now);
            empMapper.insert(emp);//插入数据

            Integer empId = emp.getId();//获取当前插入的id
            List<EmpExpr> exprlist = emp.getExprList();//获取当前插入的exprlist
            if (!CollectionUtils.isEmpty(exprlist)) {//如果exprlist不为空
                exprlist.forEach(empExpr -> empExpr.setEmpId(empId));//设置empId
                empExprMapper.insertBatch(exprlist);//批量插入
            }
        } finally {
            empLogService.insertLog(new EmpLog(null, LocalDateTime.now(), "新增员工"));
        }
    }
    @Transactional
    @Override
    public void deleteByIds(List<Integer> ids) {
    empMapper.deleteByIds(ids);
    empExprMapper.deleteByEmpIds(ids);
    }

    @Override
    public List<Emp> listAll() {
        return empMapper.selectAll();
    }

    @Override
    public PageResult logPage(Integer page, Integer pageSize, String operateEmpName, String className, String methodName, Long costTime, String methodParams, String returnValue, LocalDateTime openDateTime) {
        PageHelper.startPage(page, pageSize);

        List<OperateLog> empList = empMapper.logPage(operateEmpName, className, methodName, costTime, methodParams, returnValue, openDateTime);

        Page<OperateLog> p = (Page<OperateLog>) empList;
        return new PageResult(p.getTotal(),p.getResult());
    }


    @Override
    public Emp getById(Integer id) {
        //查询员工与工作经历信息
        Emp emp = empMapper.selectInfoById(id);
        return emp;
    }
    @Transactional
    @Override
    public void update(Emp emp) {
        //1. 更新员工信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);
        //2. 更新员工工作经历
        //先删除旧的关系
        List<Integer> ids = List.of(emp.getId());
        empExprMapper.deleteByEmpIds(ids);
        //再添加新关系
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach(e -> e.setEmpId(emp.getId()));
            empExprMapper.insertBatch(exprList);
        }
    }
}
